package com.example.cloud.service.business.medical.impl;

import com.example.cloud.constants.StateConstants;
import com.example.cloud.dao.business.medical.ExecuteRecordRepository;
import com.example.cloud.dao.business.medical.TreatPlanHomeProductRepository;
import com.example.cloud.model.business.medical.ExecuteRecord;
import com.example.cloud.model.business.medical.TreatPlanHomeProduct;
import com.example.cloud.service.basic.info.MemberService;
import com.example.cloud.service.business.medical.ExecuteService;
import com.example.cloud.service.business.medical.TreatPlanHomeProductService;
import com.example.cloud.utils.BusinessUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigDecimal;
import java.util.List;

/**
 * Created by wangtao on 2018/6/6.
 */
@Service
public class TreatPlanHomeProductServiceImpl implements TreatPlanHomeProductService {

    private static final Logger logger = Logger.getLogger(TreatPlanHomeProductServiceImpl.class);

    @PersistenceContext
    EntityManager em;

    @Autowired
    private MemberService memberService;

    @Autowired
    private ExecuteService executeService;

    @Autowired
    private ExecuteRecordRepository executeRecordRepository;

    @Autowired
    private TreatPlanHomeProductRepository treatPlanHomeProductRepository;

    @Override
    public TreatPlanHomeProduct findOne(Long id) {
        return treatPlanHomeProductRepository.findOne(id);
    }

    @Override
    public TreatPlanHomeProduct doSave(TreatPlanHomeProduct record) {
        BusinessUtil.appendRecord(record);
        return treatPlanHomeProductRepository.save(record);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doAdd(List<TreatPlanHomeProduct> records) {
        for (TreatPlanHomeProduct record : records) {
            record.setId(null);
            record.setStatus(StateConstants.HOME_STATUS_ACTIVE);
            record.setPlanType(StateConstants.PLAN_TYPE_BASIC);
            record.setTotalPrice(record.getPrice().multiply(new BigDecimal(record.getQuantity())));
            BusinessUtil.appendRecord(record);
        }
        treatPlanHomeProductRepository.save(records);
    }

    @Override
    public void doExecute(TreatPlanHomeProduct record, int status, String content) {
        ExecuteRecord executeRecord = new ExecuteRecord();
        executeRecord.setPatientId(record.getPatientId());
        executeRecord.setComplaintId(record.getComplaintId());
        executeRecord.setOrderId(record.getId());
        executeRecord.setStatus(status);
        executeRecord.setTreatType(StateConstants.EXECUTE_TREAT_TYPE_HOME);
        executeRecord.setItemType(StateConstants.EXECUTE_ITEM_TYPE_PRODUCT);
        executeRecord.setItemId(record.getProductId());
        executeRecord.setItemName(record.getProductName());
        executeRecord.setDoctorName(record.getCreatedBy());
        executeRecord.setDoctorRemark(record.getMedicalAdvice());
        executeRecord.setSource(record.getHomeName());
        executeRecord.setTotalCount(record.getQuantity());
        executeRecord.setLaveCount(record.getQuantity() - record.getExecute());
        executeRecord.setMedicalTime(record.getCreationTime());
        executeRecord.setExecuteContent(content);
        executeRecord.setCreationTime(null);
        BusinessUtil.appendRecord(executeRecord);
        executeService.doSave(executeRecord);
        // 更新已执行次数
        if(status == StateConstants.EXECUTE_STATUS_YES){
            record.setExecuteStatus(StateConstants.EXECUTE_STATUS_YES);
            BusinessUtil.appendRecord(record);
            treatPlanHomeProductRepository.save(record);
        }
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doStop(Long id) {
        StringBuilder sql = new StringBuilder("update treat_plan_home_product set `status` = :status where id = :id");
        Query nq = em.createNativeQuery(sql.toString());
        nq.setParameter("status", StateConstants.HOME_DETAILS_STATUS_STOP);
        nq.setParameter("id", id);
        nq.executeUpdate();
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doReplace(TreatPlanHomeProduct product, List<TreatPlanHomeProduct> products) {
        // 更新原有记录状态
        product.setStatus(StateConstants.HOME_DETAILS_STATUS_REPLACE);
        BusinessUtil.appendRecord(product);
        treatPlanHomeProductRepository.save(product);
        // 保存新的产品
        for (TreatPlanHomeProduct tp : products) {
            tp.setPatientId(product.getPatientId());
            tp.setMemberId(product.getMemberId());
            tp.setComplaintId(product.getComplaintId());
            tp.setHomeId(product.getHomeId());
            tp.setHomeName(product.getHomeName());
            tp.setPlanType(product.getPlanType());
            tp.setTotalPrice(tp.getPrice().multiply(new BigDecimal(tp.getQuantity())));
            tp.setStatus(StateConstants.HOME_DETAILS_STATUS_PROCESS);
            BusinessUtil.appendRecord(tp);
        }
        treatPlanHomeProductRepository.save(products);
    }

    @Override
    @Transactional(isolation = Isolation.DEFAULT)
    public void doDelete(Long id) {
        StringBuilder sql = new StringBuilder("update treat_plan_home_product set delete_flag = 1 where id = :id");
        Query nq = em.createNativeQuery(sql.toString());
        nq.setParameter("id", id);
        nq.executeUpdate();
    }
}
